`timescale 1ns / 1ps 
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 2022/03/02 20:36:27
// Design Name:
// Module Name: dif_ram
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////


module dif_ram(resetb,
               sel,
               wclk,
               wr,
               wdat,
               rclk,
               rd,
               rdat

              );
parameter ADDR_MAX = 800 * 600;
input resetb;
input sel;
input wclk;
input wr;
input wdat;
input rclk;
input rd;
output rdat;
parameter ck2q = 1;
reg [18: 0] raddr;
reg buffer [0: ADDR_MAX - 1];
reg [18: 0] waddr;
wire [18: 0] waddr_p1 = (waddr + 1'b1);
wire waddr_tc = (waddr_p1 == ADDR_MAX);
always@(posedge wclk or negedge resetb)
	begin
		if (!resetb)
			waddr <= #ck2q 0;
		else if (wr)
			begin
				if (waddr_tc)
					waddr <= #ck2q 0;
				else
					waddr <= #ck2q waddr + 1'b1;
			end
	end
wire [18: 0] raddr_p1 = (raddr + 1'b1);
wire raddr_tc = (raddr_p1 == ADDR_MAX);
always@(posedge rclk or negedge resetb)
	begin
		if (!resetb)
			raddr <= #ck2q 0;
		else if (rd & sel)
			begin
				if (raddr_tc)
					raddr <= #ck2q 0;
				else
					raddr <= #ck2q raddr + 1'b1;
			end
	end
always@(posedge wclk) if (wr)
		buffer[waddr] <= #ck2q wdat;
reg rdat;
always@(posedge rclk) if (rd)
		rdat <= #ck2q buffer[raddr];
reg en;
always@(posedge wclk or negedge resetb)
	begin
		if (!resetb)
			en <= #ck2q 0;
		else if (waddr_tc)
			en <= #ck2q ~en;
	end
endmodule
